1;

################################################################################
#                                                                             ##
#spacing                                                                      ##
#                                                                             ##
################################################################################
#using the distance defined in the frame of spacing metric
function distance = nearest_front_distance(pareto_front, solution)
    min_d_i = realmax;
    for i = 1 : rows(pareto_front)
        front_solution = pareto_front(i, :);
        d_i = 0;
        for j = 1 : columns(solution)
            d_i = d_i + abs(solution(j)) + abs(front_solution(j));
        endfor
        if (d_i < min_d_i)
            min_d_i = d_i;
        endif
    endfor
    distance = min_d_i;
endfunction

function value = spacing(real_pareto_front, pareto_front)

    d = zeros(rows(pareto_front), 1);
    sum_d = 0;
    fprintf(stderr, "evaluating spacing\n");
    for i = 1 : rows(pareto_front)
        fprintf(stderr, "\tevaluating distance ... %d/%d\r",i, rows(pareto_front));
        d(i) = nearest_front_distance(real_pareto_front, pareto_front(i,:));
        sum_d = sum_d + d(i);
    endfor
    fprintf(stderr, "\tevaluating distance ...    [done]\n");

    average_d = sum_d / rows(pareto_front);

    sum_d = 0;
    for i = 1 : rows(pareto_front)
        sum_d = sum_d + (average_d - d(i)) ^ 2;
    endfor

    value = sqrt((1 / (rows(pareto_front) - 1)) * sum_d);
endfunction
